package cn.tedu.tmall.admin.content.handler;

import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handlerRuntimeException(RuntimeException e) {
        String message = e.getMessage();
        return JsonResult.fail(message);
    }

    @ExceptionHandler
    public JsonResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer allMessage = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            allMessage.append(fieldError.getDefaultMessage());
            allMessage.append(",");
        }
        //类别名称不能太长-ByLength,类别名称不能为空-byBlank,类别名称不能为空-byEmpty,类别名称不能太长-BySize,年龄应该在18-120之间,
        return JsonResult.fail(delete(allMessage));
    }



    public String delete(StringBuffer str) {
        //StringBuilder StringBuffer 区别  StringBuffer 线程安全
        StringBuffer stringBuffer = new StringBuffer(str);
        StringBuffer delete = stringBuffer.
                delete(stringBuffer.lastIndexOf(","), stringBuffer.length());
        return delete.toString();
    }
}
